package mindteck.store;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class UserDAO extends BaseDAO{
	
	private final String GETUSERBYUSERID = "SELECT * FROM USERS WHERE USERID = ?";
	private final String INSERTUSER = "INSERT INTO USERS VALUES (?,?,?,?)";
	
	
	public UserDAO(){
		
	}
	
	
	public UserBean getUserById(int userId){
		UserBean userBean = new UserBean();
		Connection connection = null;
		PreparedStatement pst = null;
		
		try{
			connection = getPoolOfConnections();
			pst = connection.prepareStatement(GETUSERBYUSERID);
			pst.setInt(1, userId);
			ResultSet rs = pst.executeQuery();
			
			if(rs.next()){
			userBean.setUserID(rs.getInt("userId"));
			userBean.setPassword(rs.getString("password"));
			userBean.setLoginStatus(rs.getString("loginStatus"));
			userBean.setUserName(rs.getString("userName"));
			}
			
			
		}catch(SQLException exp){
			//error occured, set t to false
			
			exp.printStackTrace();
		}finally{
			if(connection != null){
				try {
					connection.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
		
		return userBean;
	}
	
	public boolean insertUser(UserBean userBean){
		boolean t = true;
		Connection connection = null;
		PreparedStatement pstatement = null;
		
		try{
			connection = getPoolOfConnections();
			pstatement = connection.prepareStatement(INSERTUSER);
			
			pstatement.setInt(1, userBean.getUserID());
			pstatement.setString(2, userBean.getUserName());
			pstatement.setString(3, userBean.getPassword());
			pstatement.setString(4, userBean.isLoginStatus());
			
			pstatement.executeQuery();
			
			
		}catch(SQLException ex){
			ex.printStackTrace();
			//set boolean to false if error occured
			t = false;
			
		}finally{
			if(connection != null){
				try {
					
					connection.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return t;
	}
	
	

}
